package com.benjaminwan.read.free.model

import android.content.Context
import android.util.AttributeSet
import android.util.TypedValue
import android.view.MotionEvent
import androidx.appcompat.widget.AppCompatButton
import com.benjaminwan.read.free.R

class Key @JvmOverloads constructor(
    context: Context,
    private val mKeyAttributes: KeyAttributes,
    attrs: AttributeSet? = null,
    defStyle: Int = 0
) : AppCompatButton(context, attrs, defStyle) {
    private var mKeyListener: KeyListener? = null

    init {
        text = "${mKeyAttributes.mainLabel}\n${mKeyAttributes.keyCode.toUByte()}"
        setDefaultConfiguration()
        setTextSize(TypedValue.COMPLEX_UNIT_SP, 10F)
    }

    class KeyAttributes {
        var keyFunction: String = ""
        var mainLabel: String = ""
        var shiftLabel: String = ""
        var keyCode: Int = 0
    }

    interface KeyListener {
        fun onKeyDown(keyFunction: String, keyCode: Int)
        fun onKeyUp(keyFunction: String, keyCode: Int)
    }

    private fun setDefaultConfiguration() {
        setPadding(1, 1, 1, 1)
    }

    fun setShiftState(shiftOn: Boolean) {
        val label = if (shiftOn) {
            mKeyAttributes.shiftLabel
        } else {
            mKeyAttributes.mainLabel
        }
        if (label != null && label.isNotEmpty()) {
            text = label
        }
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        when (event.actionMasked) {
            MotionEvent.ACTION_DOWN -> dispatchOnKeyDown()
            MotionEvent.ACTION_UP -> dispatchOnKeyUp()
        }
        return super.onTouchEvent(event)
    }

    private fun dispatchOnKeyDown() {
        if (mKeyListener != null) {
            mKeyListener!!.onKeyDown(mKeyAttributes.keyFunction, mKeyAttributes.keyCode)
        }
    }

    private fun dispatchOnKeyUp() {
        if (mKeyListener != null) {
            mKeyListener?.onKeyUp(mKeyAttributes.keyFunction, mKeyAttributes.keyCode)
        }
    }

    fun setKeyListener(keyListener: KeyListener?) {
        mKeyListener = keyListener
    }

}
